package intis

import (
	"fmt"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"hxzkx/global/model"
	"time"
)

func Init(path string) {
	ReadConfig(path)
	MysqlConn()
	RedisConn()
	go retry()
	TableAuth()
}

func TableAuth() error {
	err := model.DB.AutoMigrate(&model.User{}, &model.CommonLocation{}, &model.LocationRecord{}, &model.RouteInfo{}, &model.RouteInfoPrice{})
	if err != nil {
		fmt.Println(err)
		return err
	}
	fmt.Println("tables auth success")
	return nil
}

func retry() {
	ticker := time.Ticker{C: time.Tick(time.Second * 15)}
	for _ = range ticker.C {
		if TableAuth() != nil {
			for i := 0; i < 3; i++ {
				MysqlConn()
				if TableAuth() != nil {
					time.Sleep(time.Second * 5)
					continue
				}
				fmt.Println("retry mysql error")
			}
		}
		if model.RDB.Ping(model.Ctx).Err() != nil {
			for i := 0; i < 3; i++ {
				MysqlConn()
				if model.RDB.Ping(model.Ctx).Err() != nil {
					time.Sleep(time.Second * 5)
					continue
				}
				fmt.Println("retry Redis error")
			}
		}
	}
}

func RedisConn() {
	model.RDB = redis.NewClient(&redis.Options{
		Addr:     model.Conf.Redis.Addr,
		Password: model.Conf.Redis.Password,
	})
	if err := model.RDB.Ping(model.Ctx).Err(); err != nil {
		fmt.Println("redis connect fail", err)
	}
	fmt.Println("redis connect success")
}

func MysqlConn() {
	open, err := gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", model.Conf.Mysql.User, model.Conf.Mysql.Password, model.Conf.Mysql.Addr, model.Conf.Mysql.Database)))
	if err != nil {
		fmt.Println("mysql connect err:", err)
		return
	}
	db, _ := open.DB()
	db.SetMaxIdleConns(15)
	db.SetMaxOpenConns(25)
	db.SetConnMaxLifetime(time.Minute * 6)
	model.DB = open
	fmt.Println("mysql connect success")
}

func ReadConfig(path string) {
	viper.SetConfigFile(fmt.Sprintf("../../conf/%s.yaml", path))
	viper.ReadInConfig()
	viper.Unmarshal(&model.Conf)
	fmt.Println(model.Conf)
}
